package com.jsnj33.pdaproject.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jsnj33.pdaproject.R;
import com.jsnj33.pdaproject.adapter.FormAdapter;
import com.jsnj33.pdaproject.adapter.FormHorizontalAdapter;
import com.jsnj33.pdaproject.base.BaseActivity;
import com.jsnj33.pdaproject.bean.BatchAndProductBean;
import com.jsnj33.pdaproject.bean.ChangeBean;
import com.jsnj33.pdaproject.bean.FormGoodsBean;
import com.jsnj33.pdaproject.bean.MainBean;
import com.jsnj33.pdaproject.bean.MsgBean;
import com.jsnj33.pdaproject.constant.Constants;
import com.jsnj33.pdaproject.utils.SaNetUtils;
import com.jsnj33.pdaproject.utils.StringUtility;
import com.jsnj33.pdaproject.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.entity.StringEntity;

public class GZ_LibraryChangeActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "FormActivity";
    private final static String SCAN_ACTION = ScanManager.ACTION_DECODE;//default action

    private Vibrator mVibrator;
    private ScanManager mScanManager;
    private SoundPool soundpool = null;
    private int soundid;
    private boolean isScaning = false;
    private Button btnRetryScan;
    private TextView title;

    private RelativeLayout rProgressBar;
    private TextView tv_gh_no;
    private TextView tvPH;
    private TextView tvPM;
    private TextView tvKW;
    private LinearLayout llXCSL;
    private TextView tvXSL;
    private EditText etSJL;
    private TextView tvPiHao;
    private EditText etPiHao;
    //    private String hpm = "http://www.shiheng.com.cn?PRD_NO=372-0R5D25-800&BAT_NO=MO9929011LJF";
    private String hpm = "";
    private int state = 0;
    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            isScaning = false;
            soundpool.play(soundid, 1, 1, 0, 0, 1);
            mVibrator.vibrate(100);

            byte[] barcode = intent.getByteArrayExtra(ScanManager.DECODE_DATA_TAG);
            int barcodelen = intent.getIntExtra(ScanManager.BARCODE_LENGTH_TAG, 0);
            byte temp = intent.getByteExtra(ScanManager.BARCODE_TYPE_TAG, (byte) 0);
            String str = new String(barcode, 0, barcodelen);
            if (StringUtility.isEmpty(str)) {
                ToastUtil.showGravityToast(GZ_LibraryChangeActivity.this, "扫码失败！", Gravity.CENTER, 0, 0);
                return;
            }
            String sbs = str.substring(0, 2);
            switch (sbs) {
                //扫描货品码
                case "MO":
                case "TY":
                case "TP":
                    //作为制令单处理
//                    setGoodsData(str);
//                    os_no = str;
                    break;
                case "ht":
                    scanningProductName(str);
                    hpm = str;
                    break;
                default:
                    tv_gh_no.setText(str);
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_gz_librarychange);
        btnRetryScan = findViewById(R.id.btnRetryScan);
        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        initData();
//        scanningProductName("http://www.shiheng.com.cn?PRD_NO=372-0R5D25-800&BAT_NO=MO9929011LJF");
    }

    @Override
    protected void onResume() {
        super.onResume();
        initScan();
        IntentFilter filter = new IntentFilter();
        int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME, PropertyID.WEDGE_INTENT_DATA_STRING_TAG};
        String[] value_buf = mScanManager.getParameterString(idbuf);
        if (value_buf != null && value_buf[0] != null && !value_buf[0].equals("")) {
            filter.addAction(value_buf[0]);
        } else {
            filter.addAction(SCAN_ACTION);
        }

        registerReceiver(mScanReceiver, filter);

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mScanManager != null) {
            mScanManager.stopDecode();
            isScaning = false;
        }
        unregisterReceiver(mScanReceiver);
    }

    private void initScan() {
        mScanManager = new ScanManager();
        mScanManager.openScanner();

        mScanManager.switchOutputMode(0);
        soundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
        soundid = soundpool.load("/etc/Scan_new.ogg", 1);
    }

    private void initData() {
        title = findViewById(R.id.title);
        tv_gh_no = findViewById(R.id.tv_gh_no);
        tvPH = findViewById(R.id.tvPH);
        tvPM = findViewById(R.id.tvPM);
        tvKW = findViewById(R.id.tvKW);
        llXCSL = findViewById(R.id.llXCSL);
        tvXSL = findViewById(R.id.tvXSL);
        etSJL = findViewById(R.id.etSJL);
        etPiHao = findViewById(R.id.etPiHao);
        tvPiHao = findViewById(R.id.tvPiHao);
        rProgressBar = findViewById(R.id.rProgressBar);
        Button submit = (Button) findViewById(R.id.submit);

        submit.setOnClickListener(this);

        Intent intent = getIntent();
        if (intent != null) {
            title.setText(getIntent().getStringExtra("title"));
            state = getIntent().getIntExtra("state", 0);
            if (state == 0) {
                etPiHao.setVisibility(View.VISIBLE);
                tvPiHao.setVisibility(View.GONE);
                llXCSL.setVisibility(View.GONE);
                etSJL.setText("0");
                etSJL.setEnabled(false);
            } else {
                etPiHao.setVisibility(View.GONE);
                tvPiHao.setVisibility(View.VISIBLE);
                llXCSL.setVisibility(View.VISIBLE);

            }
        }

        btnRetryScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeInfo();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.submit:
                submitData();
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    /**
     * prd_no:扫到的货品码
     * mo_no:制令单号
     * qty:实缴数
     * user：作业人员
     * wh:仓库
     */
    private void submitData() {
        String user = tv_gh_no.getText().toString();
        if (TextUtils.isEmpty(user)) {
            ToastUtil.showToast(this, "请扫描工号");
            return;
        }
        if (TextUtils.isEmpty(hpm)) {
            ToastUtil.showToast(this, "请扫描货品码");
            return;
        }
        if (state == 0) {
            if (TextUtils.isEmpty(etPiHao.getText().toString())) {
                ToastUtil.showToast(this, "请输入批号");
                return;
            }
        }
        if (TextUtils.isEmpty(etSJL.getText().toString())) {
            ToastUtil.showToast(this, "请输入实际数量");
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("number", etSJL.getText().toString());
        map.put("stock", tvXSL.getText().toString());
        map.put("usrNo", user);
        map.put("prdNo", tvPH.getText().toString());
        map.put("state", state);
        if (state == 0) {
            map.put("batNo", etPiHao.getText().toString());
        } else {
            map.put("batNo", tvPiHao.getText().toString());
        }
        map.put("wh", tvKW.getText().toString());
        if (state == 1) {
            getHttpData(Constants.CHANGELISTADD, map);
        } else {
            getHttpData(Constants.CHANGELISTADD, map);
        }
    }

    private void getHttpData(final String url, Map<String, Object> map) {
        rProgressBar.setVisibility(View.VISIBLE);
        RequestParams requestParams = new RequestParams(url);
        String gson = new Gson().toJson(map);
        requestParams.setBodyContent(gson);
        requestParams.setAsJsonContent(true);
        x.http().post(requestParams, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                try {
                    Log.d(TAG, "getHttpData-onSuccess: " + jsonObject.toString());
                    int errCode = jsonObject.getInt("respCode");
                    String msg = jsonObject.getString("respMsg");
                    if (errCode == -1) {
                        ToastUtil.showLongGravityToast(GZ_LibraryChangeActivity.this, msg, Gravity.CENTER, 0, 0);
                    } else {
                        //请求成功
                        removeInfo();
                        ToastUtil.showToast(GZ_LibraryChangeActivity.this, "提交成功");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i(TAG, "Exception: " + e.getMessage());
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                rProgressBar.setVisibility(View.GONE);
            }
        });
    }

    private void removeInfo() {
        tvPH.setText("");
        tvPM.setText("");
        tvXSL.setText("");
        if (state != 0) {
            etSJL.setText("");
        }
        tvKW.setText("");
        tvPiHao.setText("");
        tvPiHao.setText("");
    }

    /**
     * 通过货品码获取详情
     *
     * @param barcode
     */
    private void scanningProductName(final String barcode) {

        final boolean b = judgeString(barcode);
        if (b == true) {
            ToastUtil.showGravityToast(GZ_LibraryChangeActivity.this, "二维码不存在！！！", Gravity.CENTER, 0, 0);
            return;
        }
        RequestParams requestParams = new RequestParams(Constants.CHANGELISTDETAIL);
        final JSONObject map = new JSONObject();
        try {
            map.put("barcode", barcode);
            map.put("state", state);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        requestParams.setBodyContent(map.toString());
        requestParams.setAsJsonContent(true);
        Log.d(TAG, "scanningProductName: URL:" + requestParams.getUri());
        Log.d(TAG, "scanningProductName: Params:" + map.toString());
        x.http().post(requestParams, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject result) {
                Log.d(TAG, "onSuccess: " + result.toString());
                String respCode = result.optString("respCode");
                if (respCode.equals("1")) {
                    ChangeBean bean = new Gson().fromJson(result.optString("respData"), ChangeBean.class);
                    tvPH.setText("" + bean.getPrdNo());
                    tvPM.setText("" + bean.getName());
                    tvXSL.setText("" + bean.getStock());
                    tvKW.setText("" + bean.getWh());
                    tvPiHao.setText("" + bean.getBatNo());
                } else {
                    ToastUtil.showToast(GZ_LibraryChangeActivity.this, "" + result.optString("respMsg"));
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d(TAG, "Throwable: " + ex.getMessage());

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    /**
     * 判断必传参数中是否有null或者""。
     *
     * @param str
     * @return true:有  false:无
     */
    private boolean judgeString(String... str) {
        for (int i = 0; i < str.length; i++) {
            if (StringUtility.isEmpty(str[i])) {
                return true;
            }
        }
        return false;
    }
}
